/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState, useEffect } from 'react';
import { Button, message, Space } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import KbEditLeague from '@/components/_pages/jdk/chainStores/compinents/KbEditLeague';
import KbLoginModal from '@/components/KbLoginModal';
import KbRemarksModal from '@/components/KbRemarksModal';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ConnectState } from '@/models/connect';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { CHAIN_COLUMNS } from '@/components/_pages/jdk';
import { getChainList, saveChain } from '@/services/jdk/chain';
import { chainColumns } from '@/components/_pages/jdk/index.config';
import { useSelector } from 'umi';
import styles from './index.less';

const Index = ({ show }: { show: boolean }) => {
  const actionRef = useRef<ActionType>();
  const [record, setRecord] = useState<any>();
  const [visible, setVisible] = useState<boolean>(false);
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const proFormRef = useRef<ProFormInstance>();
  const [formData, setFormData] = useState<any>();
  const [remarkItem, setRemarkItem] = useState<any>({});
  const [remarkVisible, setRemarkVisible] = useState<boolean>(false);

  const onClose = () => {
    setVisible(false);
    setRecord({});
  };
  const handelAddLeague = () => setVisible(true);
  const handleOption = (record_: any) => {
    setRecord(record_);
    handelAddLeague();
  };

  const handleRemark = (record_: any) => {
    setRemarkItem(record_);
    setRemarkVisible(true);
  };

  const onSubmit = async (values: any) => {
    if (record && record.user_id) {
      values.user_id = record?.user_id;
    }
    const { address } = values;
    values.address = JSON.stringify(address);

    saveChain(values).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        actionRef.current?.reload();
        message.success(msg);
        onClose();
      } else {
        message.error(msg);
      }
    });
  };

  const optionColumns: ProColumns<CHAIN_COLUMNS>[] = [
    {
      title: '操作',
      valueType: 'option',
      width: winSize === 'xs' ? 80 : 120,
      align: 'center',
      fixed: 'right',
      render: (_, item) => {
        const { is_black, user_id } = item;
        return (
          <Space direction='vertical'>
            <a onClick={handleOption.bind(null, item)}>修改</a>
            <KbLoginModal
              actionRef={actionRef}
              item={item}
              status={is_black == '0'}
              api={'/jdk/chain/save'}
              queryData={{ user_id, is_black: '1' }}
              inhibitedApi={'/jdk/chain/save'}
              inhibitedQueryData={{ user_id, is_black: '0' }}
            />
            <a onClick={handleRemark.bind(null, item)}>备注</a>
          </Space>
        );
      },
    },
  ];
  const queryTable = async (values: any) => {
    const { current: page, pageSize } = values;
    const { code, data, msg } = await getChainList({ page, pageSize, ...formData });
    const list = data.list.map((item: any, index: number) => ({
      ...item,
      id: index + 1,
    }));
    if (code == 0) {
      return {
        data: list,
        total: data.total,
      };
    } else {
      message.error(msg);
      return {};
    }
  };
  const onProFormSubmit = async (values: any) => {
    setFormData(values);
    actionRef.current?.reload(true);
  };
  useEffect(() => {
    if (show) actionRef.current?.reload();
  }, [show]);
  return (
    <PageContainer className={styles.main}>
      <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
        <ProForm
          formRef={proFormRef}
          layout='inline'
          onFinish={onProFormSubmit}
          initialValues={{
            department: '1',
            type: 'name',
          }}
          submitter={{
            render: (form_props: any) => {
              return [
                <Button
                  key='reset'
                  onClick={() => {
                    form_props.form?.resetFields();
                    form_props.form?.submit?.();
                  }}
                >
                  重置
                </Button>,
                <Button type='primary' key='submit' onClick={() => form_props.form?.submit?.()}>
                  查询
                </Button>,
                <Button key='add' type='primary' onClick={handelAddLeague}>
                  添加连锁商
                </Button>,
              ];
            },
          }}
        >
          <ProFormText
            fieldProps={{
              style: { width: '220px' },
            }}
            name='like_name'
            placeholder='输入连锁商名称/账号查询'
          />
        </ProForm>
      </Space>
      <DragTable>
        <ProTable
          rowKey='id'
          actionRef={actionRef}
          request={queryTable}
          columns={[...chainColumns, ...optionColumns]}
          toolBarRender={false}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          search={false}
          scroll={{
            x: 1200,
          }}
        />
        <KbEditLeague visible={visible} onSubmit={onSubmit} record={record} onClose={onClose} />
      </DragTable>
      <KbRemarksModal
        modalTitle={`添加备注 ｜ ${remarkItem.name} - ${remarkItem.phone}`}
        required
        visible={remarkVisible}
        setVisible={setRemarkVisible}
        formatDataMap={{
          label: 'operate_name',
          remark: 'remark',
          user: 'operate_phone',
          time: 'create_time',
        }}
        api='/jdk/League/leagueRemark'
        formData={{ user_id: remarkItem.user_id, type: 'chain' }}
        listApi='/jdk/League/getLeagueRemarkList'
        listFormData={{ user_id: remarkItem.user_id, type: 'chain' }}
      />
    </PageContainer>
  );
};

export default Index;
